<?php

namespace app\admin\model\user;

use think\Exception;
use think\Model;


class Spell extends Model
{





    // 表名
    protected $name = 'user_spell';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
    /**
     * 状态
     */
    public function statusInfo()
    {
        return [
            1=>'访问',
            2=>'锁定',
            3=>'使用',
            9=>'失效',
        ];
    }
    /**
     * 参加团信息
     */
    public static function addInfo($uid,$info)
    {
        $spellInfo = \app\admin\model\SpellOrder::where('id', $info['ptid'])->where('orderStatus', 2)->where('model',2)->find();
        if (empty($spellInfo)) {
            throw new Exception("团信息获取失败");
        }
        if ($info['type'] == 1){
            $fromUser = \app\common\model\User::getInviteCode($info['inviteCode']);
            if (empty($fromUser)) {
                throw new Exception("分享会员获取失败");
            }
            $fromUid = $fromUser['id'];
        }elseif($info['type'] == 2){
            $fromUid = $spellInfo['uid'];
        }
        if($fromUid == $uid){
            return true;
        }
        if(self::get(['uid'=>$uid,'ptid'=>$info['ptid'],'status'=>1])){
            return true;
        }
        $data = array(
            "uid"=>$uid,
            "type"=>$info['type'],
            "fromUid"=>$fromUid,
            "ptid"=>$info['ptid'],
            "status"=>1,
            "createtime"=>time(),
            "updatetime"=>time()
        );
        self::insert($data);
    }

    /**
     * 获取可参团数据
     */
    public static function getInfo($uid)
    {
        $info = self::where('uid',$uid)->where('type',1)->where('createtime','>',time()-86400)->where('status',1)->order('id desc')->field('id,uid,ptid,fromUid')->find();
        if(!empty($info)){
            $info->save(['status'=>2,'updatetime'=>time()]);
        }
        return $info;
    }
    /**
     * 参团信息成功参团
     */
    public static function updateSuccess($orderInfo)
    {
        $info = self::where('uid',$orderInfo['uid'])->where('ptid',$orderInfo['ptid'])->where('fromUid',$orderInfo['fromUid'])->where('status',2)->field('id,createtime')->order('id desc')->find();
        if(!empty($info)){
            $info->save(['status'=>3,'updatetime'=>time()]);
            self::where('uid',$orderInfo['uid'])->where('status',1)->where('id','<',$info['id'])->update([
                "status"=>9,
                "info"=>'参团成功系统取消'
            ]);
        }
        return true;
    }
    /**
     * 参团信息异常
     */
    public static function spellFail($info,$msg)
    {
        self::where('uid',$info['uid'])->where('ptid',$info['ptid'])->where('status',2)->update([
            "status"=>8,
            "info"=>$msg
        ]);
    }




}
